package com.haixiaoke.saas.enterprise.user.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.RepeatSubmit;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.tenant.service.ITenantService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import com.haixiaoke.saas.system.framework.web.service.SysLoginService;
import com.haixiaoke.saas.system.framework.web.service.TokenService;
import com.haixiaoke.saas.user.domain.UserBusiness;
import com.haixiaoke.saas.user.service.IUserBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author panda
 * @Date 2023/12/20
 **/
@RestController
@RequestMapping("/enterprise/user/userBusiness")
public class EnterpriseUserBusinessController extends BaseController {

    @Autowired
    private IUserBusinessService bizUserBusinessService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ITenantService tenantService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserBusiness user) {
        startPage();
        user.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        List<UserBusiness> list = bizUserBusinessService.selectUserBusListByDep(user);
        return getDataTable(list);
    }


    /**
     * 获取机构下所有用户信息
     *
     * @param user
     * @return
     */
    @GetMapping("/userList")
    public AjaxResult userList(UserBusiness user) {
        user.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        List<UserBusiness> list = bizUserBusinessService.selectUserBusListByDep(user);
        return success(list);
    }

    /**
     * 查询用户的机构集合
     *
     * @param userId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:user:query')")
    @GetMapping("/getDepListByUserId/{userId}")
    public AjaxResult getDepListByUserId(@PathVariable("userId") Long userId) {
        return success(tenantService.selectDepByUserId(userId));
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping("/{userId}")
    public AjaxResult changeStatus(@PathVariable("userId") Long userId) {
        return success(bizUserBusinessService.selectBizUserBusinessByUserId(userId, SecurityUtils.getLoginUser().getTenantId()));
    }

    @PreAuthorize("@ss.hasPermi('enterprise:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult enterpriseAdd(@Validated @RequestBody UserBusiness user) {
        if (StrUtil.isBlank(SecurityUtils.getLoginUser().getTenantId())) {
            return error("缺少机构标识");
        }
        user.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        UserBusiness userBusiness = bizUserBusinessService.selectBizUserByPhonenumber(user.getPhonenumber());
        if (ObjectUtil.isNotEmpty(userBusiness)) {
            if (StrUtil.equals(user.getTenantId(), userBusiness.getTenantId())) {
                return error("该用户已存在");
            } else {
                return error("该用户为其他机构用户");
            }
        }
        if (!bizUserBusinessService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !bizUserBusinessService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (user.getRoles() == null || user.getRoleIds().length == 0) {
            return error("角色数据异常");
        }
        if (StringUtils.isNull(user.getDeptId())) {
            return error("部门数据异常");
        }
        if (tenantService.checkPopulation(user.getTenantId())) {
            return error("该企业已达到最大人数");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        return success(bizUserBusinessService.insertBizUserBusiness(user));
    }

    @PreAuthorize("@ss.hasPermi('enterprise:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult enterpriseEdit(@Validated @RequestBody UserBusiness user) {
        if (StrUtil.isBlank(getLoginUser().getTenantId())) {
            return error("缺少机构标识");
        }
        if (user.getRoleIds() == null || user.getRoleIds().length == 0) {
            return error("角色数据异常");
        }
        if (StringUtils.isNull(user.getDeptId())) {
            return error("部门数据异常");
        }
        user.setTenantId(getLoginUser().getTenantId());
        user.setOldTenantId(getLoginUser().getTenantId());
        if (!bizUserBusinessService.checkUserNameUnique(user)) {
            return error("编辑用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !bizUserBusinessService.checkPhoneUnique(user)) {
            return error("编辑用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (bizUserBusinessService.checkByAdmin(user)) {
            return error("不能删除管理员用户的主管理员角色");
        }
        user.setUpdateBy(getUsername());
        user.setPassword(null);
        return success(bizUserBusinessService.updateBizUserBusiness(user));
    }

    /**
     * 用户修改密码
     *
     * @param user
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:user:edit')")
    @PutMapping("/editPassword")
    public AjaxResult editPassword(@RequestBody UserBusiness user) {
        user.setUpdateBy(getUsername());
        return success(bizUserBusinessService.updateBizUserPassword(user));
    }

    /**
     * 修改当前用户密码
     *
     * @param user
     * @return
     */
    @PutMapping("/activeUser/editPassword")
    public AjaxResult activeUserEditPassword(@RequestBody UserBusiness user) {
        LoginUser loginUser = getLoginUser();
        if (!SecurityUtils.matchesPassword(user.getPassword(), loginUser.getBizUser().getPassword())) {
            return error("旧密码错误");
        }
        user.setUserId(loginUser.getBizUser().getUserId());
        user.setUpdateBy(getUsername());
        int result = bizUserBusinessService.updateBizUserPassword(user);
        if (result > 0) {
            // 更新缓存用户密码
            loginUser.getBizUser().setPassword(SecurityUtils.encryptPassword(user.getNewPassword()));
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return toAjax(result);
    }

    /**
     * 用户首次登录时修改密码
     *
     * @param user
     * @return
     */
    @PutMapping("/login/editPassword")
    public AjaxResult loginEditPassword(@RequestBody UserBusiness user) {
        UserBusiness userBusiness = bizUserBusinessService.selectBizUserBusinessByUserId(getUserId(), getLoginUser().getTenantId());
        if (ObjectUtil.isNotEmpty(userBusiness)) {
            if (UserBusiness.ACTIVATE_STATUS_ACTIVATED.equals(userBusiness.getActivateStatus())) {
                return error("该账号已激活！");
            }
            user.setUserId(userBusiness.getUserId());
            int i = bizUserBusinessService.updateBizUserPassword(user);
            if (i > 0) {
                if (UserBusiness.ACTIVATE_STATUS_NOT_ACTIVATED.equals(userBusiness.getActivateStatus())) {
                    UserBusiness newUser = new UserBusiness();
                    newUser.setUserId(userBusiness.getUserId());
                    newUser.setActivateStatus(UserBusiness.ACTIVATE_STATUS_ACTIVATED);
                    bizUserBusinessService.updateUserBusState(newUser);
                }
            }
            return toAjax(i);
        }
        return error("账号不存在");
    }


    /**
     * 忘记密码
     *
     * @param user
     * @return
     */
    @PutMapping("/forget/editPassword")
    public AjaxResult forgetEditPassword(@RequestBody UserBusiness user) {
        sysLoginService.validateMobileCaptcha(user.getPhonenumber(), user.getCode(), true);
        UserBusiness userBusiness = bizUserBusinessService.selectBizUserByPhonenumber(user.getPhonenumber());
        if (ObjectUtil.isNotEmpty(userBusiness)) {
            user.setUserId(userBusiness.getUserId());
            int i = bizUserBusinessService.updateBizUserPassword(user);
            return toAjax(i);
        }
        return error("账号不存在");
    }


    /**
     * 删除用户下某个机构与用户的关联数据
     *
     * @param userId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userId}")
    @TenantScope
    public AjaxResult remove(@PathVariable("userId") Long userId) {
        return toAjax(bizUserBusinessService.deleteBizUserBusinessByUserId(userId, SecurityUtils.getLoginUser().getTenantId()));
    }

    @GetMapping("/checkUser/{phonenumber}")
    public AjaxResult checkUser(@PathVariable String phonenumber) {
        return bizUserBusinessService.checkUser(phonenumber);
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/editUser")
    @RepeatSubmit
    public AjaxResult editUser(@RequestBody UserBusiness user) {
        LoginUser loginUser = getLoginUser();
        UserBusiness bizUser = loginUser.getBizUser();
        user.setUserName(bizUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !bizUserBusinessService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !bizUserBusinessService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(bizUser.getUserId());
        user.setPassword(null);
        if (bizUserBusinessService.updateBizUser(user) > 0) {
            // 更新缓存用户信息
            if (StrUtil.isNotBlank(user.getNickName())) {
                bizUser.setNickName(user.getNickName());
            }
            if (StrUtil.isNotBlank(user.getPhonenumber())) {
                bizUser.setPhonenumber(user.getPhonenumber());
            }
            if (StrUtil.isNotBlank(user.getEmail())) {
                bizUser.setEmail(user.getEmail());
            }
            if (StrUtil.isNotBlank(user.getSex())) {
                bizUser.setSex(user.getSex());
            }
            if (StrUtil.isNotBlank(user.getAvatar())) {
                bizUser.setAvatar(user.getAvatar());
            }
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }
}
